﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
using ecdl.demo.model.expression;

using Ninject;

namespace ecdl.demo.model.expression {
    public class FileExistsInZipCondition : Expression {

        private IVolumeProvider volumeProvider;

        public string FileName { get; set; }

        private string zipName;

        public string ZipName {
            get { return zipName; }
            set { 
                zipName = volumeProvider.GetFullPath(value); 
            }
        }

        public FileExistsInZipCondition() {

        }

        [Inject]
        public FileExistsInZipCondition(IVolumeProvider volumeProvider) {
            this.volumeProvider = volumeProvider;
        }

        public override ExpressionState Evaluate(ExpressionContext context) {
            
            bool found = false;
            LeafExpressionState state = new LeafExpressionState(this);
            if (System.IO.File.Exists(ZipName)) {
                ZipFile zip = new ZipFile(ZipName);
                found = zip.FindEntry(FileName, false) >= 0;
                zip.Close();
            }

            SetCauses(state);
            state.IsOk = found;
            
            return state;
        }

        private void SetCauses(LeafExpressionState state) {
            String positive = String.Format("Das Archiv {0} muss die Datei {1} beinhalten.", ZipName, FileName);
            String negative = String.Format("Das Archiv {0} darf die Datei {1} nicht beinhalten.", ZipName, FileName);
            state.SetCause(positive, negative);
        }


    }

    public class FileExistsInZipConditionDTO : ExpressionDTO {

        [XmlAttribute("fileName")]
        public string FileName { get; set; }

        [XmlAttribute("zipName")]
        public string ZipName { get; set; }

        public override Expression ToModel(persistence.ModelFactory factory) {
            FileExistsInZipCondition condition = factory.CreateModel<FileExistsInZipCondition>();
            condition.FileName = FileName;
            condition.ZipName = ZipName;
            return condition;
        }
    }
}
